package com.yixuan.mt.common.service.impl_mysql;

import com.yixuan.mt.common.cache.BucketsCache;
import com.yixuan.mt.common.constant.BucketsConstant;
import com.yixuan.mt.common.entity.Bucket;
import com.yixuan.mt.common.exception.HttpBadRequestException;
import com.yixuan.mt.common.mapper.BucketsMapper;
import com.yixuan.mt.common.pojo.BucketsCachedData;
import com.yixuan.mt.common.service.BucketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class BucketsServiceMysqlImpl implements BucketsService {

    @Autowired
    private BucketsMapper bucketsMapper;

    @Autowired
    private BucketsCache bucketsCache;

    @Override
    public void postBuckets(String bucketName) {
        /* 整合 bucket 数据 */
        Bucket bucket = new Bucket();
        bucket.setName(bucketName);
        bucket.setAccessPolicy(BucketsConstant.BUCKET_DEFAULT_ACCESS_POLICY);
        // 创建DateTimeFormatter对象，指定目标格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 格式化当前日期时间
        String formattedDate = now.format(formatter);
        bucket.setCreatedTime(formattedDate);

        bucketsMapper.insertBucket(bucket);
        bucketsCache.setBucketsCachedData(bucketName, new BucketsCachedData(bucket.getAccessPolicy()));
    }

    @Override
    @Transactional
    public void deleteBuckets(String bucketName) {
        // 这里删除失败后还去获取对象的数量进行判断的原因：有可能删除失败的原因是没有对应的桶
        if (bucketsMapper.deleteBucket(bucketName) == 0) {
            Integer objectNum = bucketsMapper.selectObjectNum(bucketName);
            if (objectNum != null && !objectNum.equals(0)) {
                throw new HttpBadRequestException("桶中还有对象！");
            }
        }
        // 删除缓存数据
        bucketsCache.deleteBucketsCachedData(bucketName);
    }

    @Override
    public void putBuckets(Bucket bucket) {
        bucketsMapper.updateBuckets(bucket);
        // 更新缓存
        if (bucket.getAccessPolicy() != null) {
            bucketsCache.setBucketAccessPolicy(bucket.getName(), bucket.getAccessPolicy());
        }
    }

    @Override
    public List<Bucket> getBuckets() throws IOException {
        return bucketsMapper.getBuckets();
    }

    @Override
    public Bucket getBucketsSummary(String bucketName) {
        return bucketsMapper.selectBucketsSummary(bucketName);
    }
}
